#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <net/if.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <sys/socket.h>

char *ioctl_get(char *ifname, int action, char *value)
{
	struct ifreq ifr;
	struct sockaddr_in *addr;

	int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
	if (sock == -1) {
		return NULL;
	}

	strcpy(ifr.ifr_name, ifname);
	switch(action){
		case SIOCGIFADDR:
			if (ioctl(sock, SIOCGIFADDR, &ifr) >= 0) {
				addr = (struct sockaddr_in *)&ifr.ifr_addr;
				sprintf(value,"%s",(char *)inet_ntoa(addr->sin_addr));
			}
			break;
		case SIOCGIFBRDADDR:
			if (ioctl(sock, SIOCGIFBRDADDR, &ifr) >= 0) {
				addr = (struct sockaddr_in *)&ifr.ifr_broadaddr;
				sprintf(value,"%s",(char *)inet_ntoa(addr->sin_addr));
			}
			break;
		case SIOCGIFNETMASK:
			if (ioctl(sock, SIOCGIFNETMASK, &ifr) >= 0) {
				addr = (struct sockaddr_in *)&ifr.ifr_netmask;
				sprintf(value,"%s",(char *)inet_ntoa(addr->sin_addr));
			}
			break;
	}

	return value;
}

void main(int argc, char **argv)
{
	char ip[32] = {0};
	char broadcast[32] = {0};
	char netmask[32] = {0};

	printf("ip address: [%s]\n",ioctl_get("ens33", SIOCGIFADDR, ip));
	printf("broadcase address: [%s]\n",ioctl_get("ens33", SIOCGIFBRDADDR, broadcast));
	printf("netmask address: [%s]\n",ioctl_get("ens33", SIOCGIFNETMASK, netmask));
}
